package com.huika.dealontop.control.shops.holder;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.support.v4.view.AutoScrollViewPager;
import android.support.v4.view.PagerData;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.ZoomButtonsController;

import com.huika.dealontop.R;
import com.huika.dealontop.control.base.BaseAda;
import com.huika.dealontop.control.base.extend.BaseViewHolder;
import com.huika.dealontop.control.nearby.activity.GMapActivity;
import com.huika.dealontop.control.nearby.activity.MerchantDetailActivity;
import com.huika.dealontop.control.shops.activity.SubmitOrderActivity;
import com.huika.dealontop.control.shops.activity.UseBonusActivity;
import com.huika.dealontop.support.domain.ProductDetailsBean;
import com.huika.dealontop.utils.DateTimeTool;
import com.huika.dealontop.utils.DialogUtils;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.IOSAlertDialog;
import com.huika.dealontop.views.MMAlert;
import com.huika.dealontop.views.ToastMsg;
import com.huika.dealontop.views.webview.CustomWebView;
import com.huika.huikalib.utils.MoneyShowTool;
import com.huika.huikalib.utils.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Author: Victor Wu <br/>
 * Email: victor-wu*foxmail.com <br/>
 * Time: 2015/11/20 20:12 <br/>
 * Description: 团购详情  头部部分内容 控制器
 */
public class ProductDetailHeaderHolder extends BaseViewHolder<ProductDetailsBean> implements View.OnClickListener, AdapterView.OnItemClickListener {

    public static final int PRODUCT_PAGE = 0;
    public static final int COMMENTS_PAGE = 1;
    public static final int NOTICE_PAGE = 2;

    private AutoScrollViewPager autoScrollViewPager;
    private TextView mTvTitle;
    private TextView mTvTimeLeft;
    private TextView mTvBought;
    private TextView mTvPackage;
    private View mPackageUnderLine;
    private TextView mTvPrice;
    private TextView mTvDiscount;
    private TextView mTvMerchantName;
    private TextView mTvTel;
    private TextView mTvLocation;
    private Button mBtnBuy;

    //指示器
    private TextView mTvIndicatorProduct;
    private TextView mTvIndicatorComments;
    private TextView mTvIndicatorNotice;
    private View mIndicatorProduct;
    private View mIndicatorComments;
    private View mIndicatorNotice;

    //指示器下的内容
//    private TextView tv_merchant_instructions;
    private View ll_merchant_score_area;
    private FrameLayout fl_notice_area;

    private LinearLayout ll_other_coupon_title;

    //评分相关
    private RatingBar mRbTaste;
    private RatingBar mRbEnvironment;
    private RatingBar mRbService;
    private TextView mTvTaste;
    private TextView mTvEnvironment;
    private TextView mTvService;
    private TextView tv_total_score;
    private TextView tv_score_count;


    private IOSAlertDialog callDialog;

    private int packageIndex;
    private CustomWebView mWebView;

    public int getPackageIndex() {
        return packageIndex;
    }

    private int currPage = -1;
    private OnPageChangedListener onPageChangedListener;
    private OnPackageChangedListener onPackageChangedListener;

    public void setOnPackageChangedListener(OnPackageChangedListener onPackageChangedListener) {
        this.onPackageChangedListener = onPackageChangedListener;
    }

    public void setOnPageChangedListener(OnPageChangedListener onPageChangedListener) {
        this.onPageChangedListener = onPageChangedListener;
        //初始化
        refreshPage(PRODUCT_PAGE);
    }

    public interface OnPageChangedListener {
        void onPageChanged(int page);
    }
    public interface OnPackageChangedListener {
        void onPackageChanged(ProductDetailsBean.PackageSelectBean packageSelectBean, int packageIndex);
    }

    public ProductDetailHeaderHolder(Context context) {
        super(context);
    }

    @Override
    protected View initView() {
        return View.inflate(UIUtils.getContext(), R.layout.holder_product_detail_header, null);
    }

    @Override
    protected void assignView(View rootView) {
        if (rootView != null) {
            autoScrollViewPager = (AutoScrollViewPager) rootView.findViewById(R.id.avp_product_detail_banner);
            autoScrollViewPager.setScaleType(ImageView.ScaleType.CENTER_CROP);
            autoScrollViewPager.setIndicatorTwoOrMore(true);
            mTvTitle = (TextView) rootView.findViewById(R.id.tv_product_detail_title);
            mTvTimeLeft = (TextView) rootView.findViewById(R.id.tv_product_detail_time_left);
            mTvBought = (TextView) rootView.findViewById(R.id.tv_product_detail_bought);
            mTvPackage = (TextView) rootView.findViewById(R.id.tv_product_detail_package);
            mPackageUnderLine = rootView.findViewById(R.id.package_under_line);
            mTvPrice = (TextView) rootView.findViewById(R.id.tv_product_detail_price);
            mTvDiscount = (TextView) rootView.findViewById(R.id.tv_product_detail_discount);
            mTvMerchantName = (TextView) rootView.findViewById(R.id.tv_product_detail_merchant_name);
            mTvTel = (TextView) rootView.findViewById(R.id.tv_product_detail_tel);
            mTvLocation = (TextView) rootView.findViewById(R.id.tv_product_detail_location);
            mBtnBuy = (Button) rootView.findViewById(R.id.btn_product_detail_buy);

            //切换 indicator 部分
            mTvIndicatorProduct = (TextView) rootView.findViewById(R.id.tv_indicator_product);
            mTvIndicatorComments = (TextView) rootView.findViewById(R.id.tv_indicator_comments);
            mTvIndicatorNotice = (TextView) rootView.findViewById(R.id.tv_indicator_notice);
            mTvIndicatorProduct.setOnClickListener(this);
            mTvIndicatorComments.setOnClickListener(this);
            mTvIndicatorNotice.setOnClickListener(this);
            mIndicatorProduct = rootView.findViewById(R.id.indicator_product);
            mIndicatorComments = rootView.findViewById(R.id.indicator_comments);
            mIndicatorNotice = rootView.findViewById(R.id.indicator_notice);

            //指示器下的内容
//            tv_merchant_instructions = (TextView) rootView.findViewById(R.id.tv_merchant_instructions);
            initWebView();
            ll_merchant_score_area = rootView.findViewById(R.id.ll_merchant_score_area);
            fl_notice_area = (FrameLayout) rootView.findViewById(R.id.fl_notice_area);

            //其他团购
            ll_other_coupon_title = (LinearLayout) rootView.findViewById(R.id.ll_other_coupon_title);

            //评分相关
            mRbTaste = (RatingBar) rootView.findViewById(R.id.rb_taste);
            mRbEnvironment = (RatingBar) rootView.findViewById(R.id.rb_environment);
            mRbService = (RatingBar) rootView.findViewById(R.id.rb_service);
            mTvTaste = (TextView) rootView.findViewById(R.id.tv_taste);
            mTvEnvironment = (TextView) rootView.findViewById(R.id.tv_environment);
            mTvService = (TextView) rootView.findViewById(R.id.tv_service);
            tv_total_score = (TextView) rootView.findViewById(R.id.tv_total_score);
            tv_score_count = (TextView) rootView.findViewById(R.id.tv_comments_count);

            mTvPackage.setOnClickListener(this);
            mTvMerchantName.setOnClickListener(this);
            mTvTel.setOnClickListener(this);
            mTvLocation.setOnClickListener(this);
            mBtnBuy.setOnClickListener(this);

        }
        //初始化
        refreshPage(PRODUCT_PAGE);
    }

    private void initWebView() {
        mWebView = (CustomWebView) findViewById(R.id.wv_product_introduction);
        mWebView.getSettings().setDefaultTextEncodingName("utf-8");
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                mWebView.setVerticalScrollBarEnabled(false);
                mWebView.setVerticalScrollbarOverlay(false);
                mWebView.setHorizontalScrollBarEnabled(false);
                mWebView.setHorizontalScrollbarOverlay(false);
                mWebView.setBackgroundColor(Color.parseColor("#ffffff"));
                hideBuiltInZoomControls(mWebView);
                mWebView.setCanTouchZoom(false);
                // 不会闪黑屏
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                WebSettings settings = mWebView.getSettings();
                settings.setUseWideViewPort(true);
                settings.setLoadWithOverviewMode(true);
                settings.setSupportZoom(true);
                settings.setJavaScriptEnabled(true);
                settings.setTextSize(WebSettings.TextSize.NORMAL);
            }
        });
    }

    private void hideBuiltInZoomControls(WebView view) {
        if (Build.VERSION.SDK_INT < 11) {
            try {
                Field field = WebView.class.getDeclaredField("mZoomButtonsController");
                field.setAccessible(true);
                ZoomButtonsController zoomCtrl = new ZoomButtonsController(view);
                zoomCtrl.getZoomControls().setVisibility(View.GONE);
                field.set(view, zoomCtrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                WebSettings settings = view.getSettings();
                Method method = WebSettings.class.getMethod("setDisplayZoomControls", boolean.class);
                method.invoke(settings, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void refreshView(ProductDetailsBean data) {
        mData = data;
        List<PagerData> datas = getBannerBean(data.getProductPicUrlList());
        if (datas != null) {
            autoScrollViewPager.setDatas(datas,
                    (LinearLayout) mRootView.findViewById(R.id.ll_product_detail_banner_indicator), true, true);
        }
        if (mData.getPackageSelect() != null && mData.getPackageSelect().size() > 1) {
            ProductDetailsBean.PackageSelectBean packageSelectBean = getPackage();
            mTvPackage.setText(packageSelectBean.getSkuName());
        }else{
            //隐藏套餐选择
            mTvPackage.setVisibility(View.GONE);
            mPackageUnderLine.setVisibility(View.GONE);
        }

        ProductDetailsBean.ProductBean product = data.getProduct();
        if (product != null) {
            mTvTitle.setText(product.getProductName());
            new ProductCountDownTimer(((long) product.getSurplusTime())).start();
//            mTvTimeLeft.setText(DateTimeTool.getCountdownTimeMDHMS((long) product.getSurplusTime()));
            mTvBought.setText(UIUtils.getFormatString(R.string.some_people_buy, product.getPurchasedNum()));
            mTvPrice.setText(MoneyShowTool.nolastDF(product.getSalePrice()));
            if(product.getDiscount() > 0) {
                mTvDiscount.setText(MoneyShowTool.nolastDF(product.getDiscount(), false) + "% Off");
            }
            mTvMerchantName.setText(product.getMerchantName());
            mTvTel.setText(StringUtils.formatTaiPhone(getDisplayPhoneNumber()));
            mTvLocation.setText(product.getMerchantAddress());

            //////////指示器下面信息
            try {
//                tv_merchant_instructions.setText(Html.fromHtml(product.getProductIntroduction()));
                mWebView.loadData(product.getProductIntroduction(),"text/html;charset='utf-8'", "utf-8");
            }catch (Throwable t){
            }
            //须知信息
            ProductNoticeHolder noticeHolder = new ProductNoticeHolder(mContext);
            noticeHolder.setData(product);
            fl_notice_area.addView(noticeHolder.getRootView());


            //评分
            if(product.getTotalPriceScore() == 0){
                product.setTotalPriceScore(5);
            }
            if(product.getTotalEnvironmentScore() == 0){
                product.setTotalEnvironmentScore(5);
            }
            if(product.getTotalServiceScore() == 0){
                product.setTotalServiceScore(5);
            }
            mRbTaste.setRating((float) product.getTotalPriceScore());
            mRbEnvironment.setRating((float) product.getTotalEnvironmentScore());
            mRbService.setRating((float) product.getTotalServiceScore());
            mTvTaste.setText(MoneyShowTool.formatOne(product.getTotalPriceScore()));
            mTvEnvironment.setText(MoneyShowTool.formatOne(product.getTotalEnvironmentScore()));
            mTvService.setText(MoneyShowTool.formatOne(product.getTotalServiceScore()));

            if(product.getTotalScore() == 0){
                product.setTotalScore(5);
            }
            tv_total_score.setText(MoneyShowTool.formatOne(product.getTotalScore()));
            tv_score_count.setText(UIUtils.getFormatString(R.string.Merchant_pingjianum, product.getCommentCount()));
        }
    }
    private String retDate = "";
    class ProductCountDownTimer extends CountDownTimer{
        public ProductCountDownTimer(long millisInFuture) {
            super(millisInFuture, 1000); //一秒更新一次
        }
        @Override
        public void onTick(long millisInFuture) {
            try {
                retDate = DateTimeTool.getCountdownTimeMDHMS(millisInFuture / 1000);
            } catch (Exception e) {
                retDate = "";
                cancel();
            }finally {
                mTvTimeLeft.setText(retDate);
            }
        }
        @Override
        public void onFinish() {
            mTvTimeLeft.setText(UIUtils.getString(R.string.time_out));
        }
    }

    private String getDisplayPhoneNumber(){
        ProductDetailsBean.ProductBean product;
        if(mData == null || (product = mData.getProduct()) == null){
            return "";
        }
        return !StringUtils.isEmpty(product.getMerchantPhone()) ? product.getMerchantPhone() :
                !StringUtils.isEmpty(product.getMerchantTel()) ? product.getMerchantTel() : "";
    }

    private List getBannerBean(List<String> productPicUrlList) {
        if (productPicUrlList == null) {
            return null;
        }
        List<PagerData> datas = new ArrayList<>();
        PagerData data;
        for (String item : productPicUrlList) {
            data = new PagerData() {
                private String imgUrl;

                @Override
                public String getImageUrl() {
                    return imgUrl;
                }

                @Override
                public void setImageUrl(String imgUrl) {
                    this.imgUrl = imgUrl;
                }
            };
            data.setImageUrl(item);
            datas.add(data);
        }
        return datas;
    }

    /**
     * @return
     */
    protected String getPackageName() {
        ProductDetailsBean.PackageSelectBean aPackage = getPackage();
        if (aPackage != null) {
            return aPackage.getSkuName();
        }
        return null;
    }

    /**
     * @return
     */
    public ProductDetailsBean.PackageSelectBean getPackage() {
        if (mData.getPackageSelect() != null && mData.getPackageSelect().size() > packageIndex) {
            return mData.getPackageSelect().get(packageIndex);
        }
        return null;
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_product_detail_package) {
            //选择套餐
            showPackageDialog();
        } else if (id == R.id.tv_product_detail_merchant_name) {
            //商家主页
            ProductDetailsBean.ProductBean productBean = null;
            if(mData == null || (productBean = mData.getProduct()) == null){
                return;
            }
            Intent intent = new Intent(mContext,MerchantDetailActivity.class);
            intent.putExtra(MerchantDetailActivity.Product_ID, String.valueOf(productBean.getProductId()));
            intent.putExtra(MerchantDetailActivity.Merchant_ID, String.valueOf(productBean.getMerchantID()));
            mContext.startActivity(intent);

        } else if (id == R.id.tv_product_detail_tel) {
            final String number = getDisplayPhoneNumber();
            if(!TextUtils.isEmpty(number)) {
                if(callDialog == null){
                    callDialog = DialogUtils.getInstance().createTitleDialog(mContext, StringUtils.formatTaiPhone(number));
                    callDialog.setCancelText(UIUtils.getString(R.string.common_calcle));
                    callDialog.setConfirmText(UIUtils.getString(R.string.comm_call_phone));
                    callDialog.setConfirmClickListener(new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            callDialog.dismiss();
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + number));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(intent);
                        }
                    });
                }
                callDialog.show();
            }
            //打电话
        } else if (id == R.id.tv_product_detail_location) {
            ProductDetailsBean.ProductBean productBean;
            if (mData == null || (productBean = mData.getProduct()) == null) {
                return;
            }
            //打开地图
            Intent intent = new Intent(mContext, GMapActivity.class);
            intent.putExtra(GMapActivity.MERCHANTNAME,productBean.getMerchantName());
            intent.putExtra(GMapActivity.MERCHANTADDRESS,productBean.getMerchantAddress());
            intent.putExtra(GMapActivity.MERCHANTLAT,productBean.getLatitude());
            intent.putExtra(GMapActivity.MERCHANTLNG,productBean.getLongitude());
            Log.d("cy","详情经度："+productBean.getLatitude()+"详情维度："+productBean.getLongitude());
            mContext.startActivity(intent);
        } else if (id == R.id.btn_product_detail_buy) {
            ProductDetailsBean.ProductBean productBean;
            if (mData == null || (productBean = mData.getProduct()) == null) {
                return;
            }
            ProductDetailsBean.PackageSelectBean packageSelectBean = getPackage();
            if(packageSelectBean == null || packageSelectBean.getStock() < 1){
                ToastMsg.showToastMsg(mContext, UIUtils.getString(R.string.under_stock));
                return;
            }
            //购买
            Intent intent = new Intent(mContext, SubmitOrderActivity.class);
            intent.putExtra(GMapActivity.MERCHANTNAME,productBean.getProductName());
            intent.putExtra(GMapActivity.MERCHANTLNG,productBean.getLongitude());
//            intent.putExtra(SubmitOrderActivity.SALEPRICE,productBean.getSalePrice());
            intent.putExtra(UseBonusActivity.CITYID,productBean.getCityId());
            if(packageSelectBean != null){
                intent.putExtra(SubmitOrderActivity.PRODUCT_SKUID, packageSelectBean.getSKU_ProducId());
                intent.putExtra(SubmitOrderActivity.PRODUCT_SKUNAME,packageSelectBean.getSkuName());
                intent.putExtra(SubmitOrderActivity.PRODUCT_STOCK,packageSelectBean.getStock());
                intent.putExtra(SubmitOrderActivity.SKUPRICE, packageSelectBean.getSkuHKPrice());
            }
            mContext.startActivity(intent);
        }else if(id == R.id.tv_package_cancel){
            if(mPackageDialog != null && mPackageDialog.isShowing()){
                mPackageDialog.dismiss();
            }
        }else if(id == R.id.tv_indicator_product){
            refreshPage(PRODUCT_PAGE);
        }else if(id == R.id.tv_indicator_comments){
            refreshPage(COMMENTS_PAGE);
        }else if(id == R.id.tv_indicator_notice){
            refreshPage(NOTICE_PAGE);
        }
    }

    private void refreshPage(int page) {
        if(currPage != page){
            currPage = page;
            mTvIndicatorProduct.setTextColor(currPage == PRODUCT_PAGE ? UIUtils.getColor(R.color.color_fe722f) : UIUtils.getColor(R.color.color_333333));
            mTvIndicatorComments.setTextColor(currPage == COMMENTS_PAGE ? UIUtils.getColor(R.color.color_fe722f) : UIUtils.getColor(R.color.color_333333));
            mTvIndicatorNotice.setTextColor(currPage == NOTICE_PAGE ? UIUtils.getColor(R.color.color_fe722f) : UIUtils.getColor(R.color.color_333333));
            mIndicatorProduct.setVisibility(currPage == PRODUCT_PAGE ? View.VISIBLE : View.INVISIBLE);
            mIndicatorComments.setVisibility(currPage == COMMENTS_PAGE ? View.VISIBLE : View.INVISIBLE);
            mIndicatorNotice.setVisibility(currPage == NOTICE_PAGE ? View.VISIBLE : View.INVISIBLE);

            mWebView.setVisibility(currPage == PRODUCT_PAGE ? View.VISIBLE : View.GONE);
            ll_merchant_score_area.setVisibility(currPage == COMMENTS_PAGE ? View.VISIBLE : View.GONE);
            fl_notice_area.setVisibility(currPage == NOTICE_PAGE ? View.VISIBLE : View.GONE);
            ll_other_coupon_title.setVisibility(currPage == PRODUCT_PAGE ? View.VISIBLE : View.GONE);

            if(onPageChangedListener != null){
                onPageChangedListener.onPageChanged(currPage);
            }
        }
    }

    /****************************  套餐选择 ***********************************/
    private Dialog mPackageDialog;
    private View packageDialogCancel;
    private ListView mLvPackageList;
    private PackageAdapter packageAdapter;
    private void showPackageDialog() {
        if (mData == null || mData.getPackageSelect() == null ||  mData.getPackageSelect().size() < 1) {
            return;
        }
        if(mPackageDialog == null){
            mPackageDialog = MMAlert.createShowAlert(mContext,R.layout.choose_package_layout);
            mLvPackageList = (ListView) mPackageDialog.findViewById(R.id.lv_package_list);
            packageDialogCancel = mPackageDialog.findViewById(R.id.tv_package_cancel);
            mPackageDialog.findViewById(R.id.tv_package_cancel).setOnClickListener(this);
            packageAdapter = new PackageAdapter(mContext);
            packageAdapter.setGroup(mData.getPackageSelect());
            //初始化默认选中的
            getPackage().isSelect = true;
            mLvPackageList.setAdapter(packageAdapter);
            mLvPackageList.setOnItemClickListener(this);
        }
        if(mPackageDialog.isShowing()){
            mPackageDialog.dismiss();
        }
        mPackageDialog.show();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if(adapterView.getId() == R.id.lv_package_list){
            List<ProductDetailsBean.PackageSelectBean> list = packageAdapter.getGroup();
            for (int a = 0 ; a < list.size(); a++){
                list.get(a).isSelect = false;
            }
            packageIndex = i;
            packageAdapter.getItem(i).isSelect = true;
            packageAdapter.notifyDataSetChanged();
            mPackageDialog.dismiss();

            refreshPackage();
        }
    }

    private void refreshPackage() {
        mTvPackage.setText(getPackage().getSkuName());
        mTvPrice.setText(MoneyShowTool.nolastDF(getPackage().getSkuHKPrice()));
        mTvDiscount.setText(MoneyShowTool.nolastDF(getPackage().getDiscount()) + "% Off");
        if(onPackageChangedListener != null){
            onPackageChangedListener.onPackageChanged(getPackage(), packageIndex);
        }
    }

    public class PackageAdapter extends BaseAda<ProductDetailsBean.PackageSelectBean>{

        public PackageAdapter(Context context) {
            super(context);
        }

        public List<ProductDetailsBean.PackageSelectBean> getGroup(){
            return group;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder vh;
            if (view == null) {
                view = View.inflate(UIUtils.getContext(), R.layout.item_package_list, null);
                vh = new ViewHolder(view);
                view.setTag(vh);
            } else {
                vh = (ViewHolder) view.getTag();
            }
            ProductDetailsBean.PackageSelectBean bean = getItem(i);
            vh.tv_name.setText(bean.getSkuName());
            vh.checkBox.setBackgroundResource(bean.isSelect ? R.mipmap.tick_language : R.color.color_transparent);
            return view;
        }
    }

    class ViewHolder {
        public TextView tv_name;
        public ImageView checkBox;

        public ViewHolder(View view) {
            tv_name = (TextView) view.findViewById(R.id.tv_select_name);
            checkBox = (ImageView) view.findViewById(R.id.iv_select_icon);
        }
    }
    /****************************  套餐选择  end ***********************************/

}
